package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiSupplierEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.SupplierDao;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierSubDataModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author WangJian
 * @date  2019-01-25 13:57
 **/
@Service("SupplierModel")
public class SupplierModelImpl implements SupplierModel{
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private SupplierDao supplierDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private SupplierSubDataModel supplierSubDataModel;
    @Resource
    private ExplainHelp explainHelp;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(SupplierEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = supplierDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(SupplierEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer integer = supplierDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        if (Objects.equals(1, integer) || Objects.equals(1, updateSub)) {
            // 更新时间
            integer = supplierDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return integer;
    }

    @Override
    public List<SupplierEntityExt> findEntitys(Map<String, Object> param) {
        List<SupplierEntityExt> entitys = supplierDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return supplierDao.getEntitysCount(param);
    }

    /**
     * 查询单个实体
     *
     */
    @Override
    public SupplierEntityExt getByKey(Long key, String corpid) {
        SupplierEntityExt supplierEntityExt = supplierDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(supplierEntityExt), IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        return supplierEntityExt;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> supplierIdIn, String corpid) throws XbbException {
        Integer integer = supplierDao.deleteBatch(supplierIdIn, corpid);
        paasEsModel.deleteBatch(supplierIdIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_SUPPLIER);

        paasFormSubDataModel.deleteBatchByDataId(supplierIdIn, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        return supplierDao.deleteByKey(key,corpid);
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = supplierDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_SUPPLIER);
        }
        if (!subList.isEmpty()) {
            supplierSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = supplierDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_SUPPLIER, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            supplierSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List<AiSupplierEntity> getSupplierList4Ai(String corpid, List<Long> idIn) {
        return supplierDao.getSupplierList4Ai(corpid, idIn);
    }

    /**
     * 在供应商名称是唯一的情况下，可以使用名称来查询
     *
     * @param corpid
     * @param supplierName
     * @return
     * @throws XbbException
     */
    @Override
    public SupplierEntityExt getBySupplierName(String corpid, String supplierName) throws XbbException {
        SupplierEntityExt supplierEntityExt = supplierDao.getBySupplierName(corpid, supplierName);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(supplierEntityExt), IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
        return supplierEntityExt;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return supplierDao.findEntitys(param);
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     * @author Jian.Wang
     * @date 2019-02-25 21:23
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        formatAddExplain(formatExplainDTO);
    }

    /**
     *  向字段中加入新的字段
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatAddExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setEditable(0);
                fieldAttrEntity.setRequired(0);
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.SUPPLIER, corpid, OperatePageEnum.NEW.getCode(), false);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), SupplierEnum.PHONE.getAttr())){
                // 补救之前供应商之前的showtype默认为1的情况，最大限度的保留客户数据
                if(Objects.nonNull(fieldAttrEntity)){
                    SubFormPoJo supplierPhoneSubForm = fieldAttrEntity.getSubForm();
                    if(Objects.nonNull(supplierPhoneSubForm)){
                        List<? extends FieldAttrEntity> items = supplierPhoneSubForm.getItems();
                        if(!items.isEmpty()){
                            Iterator<? extends FieldAttrEntity> iterator = items.iterator();
                            while (iterator.hasNext()) {
                                FieldAttrEntity subField = iterator.next();
                                if(Objects.nonNull(subField.getShowType())){
                                    subField.setShowType(ShowTypeEnum.ALL.getCode());
                                }
                            }
                        }
                    }
                }
            } else if ( Objects.equals(fieldAttrEntity.getAttr(), SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr())) {
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SUPPLIER_CONTACT_VIEW.getAlias()) ) {
                    fieldAttrEntity.setVisible(0);
                }
                if ( !formatExplainDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SUPPLIER_CONTACT_ADD.getAlias()) ) {
                    fieldAttrEntity.setEditable(0);
                }
            }
        }
    }

    /**
     * 供应商编辑格式化数据格式
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 参数格式错误异常
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {

    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.SUPPLIER, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = supplierDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER);
        paasEsModel.update(insertDTO);
        return success;
    }
}
